package com.javatiaocao.myblog.service.impl;

import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.StatisticMapper;
import com.javatiaocao.myblog.mapper.UserMapper;
import com.javatiaocao.myblog.model.ArticleLikesRecord;
import com.javatiaocao.myblog.model.User;
import com.javatiaocao.myblog.service.LikeService;
import com.javatiaocao.myblog.utils.DataMap;
import com.javatiaocao.myblog.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class LikeServiceImpl implements LikeService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    StatisticMapper statisticMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public DataMap addArticleLike(ArticleLikesRecord articleLikesRecord, UserDetails userDetails) {
        TimeUtil timeUtil = new TimeUtil();
        User user = userMapper.findUserByPhone(userDetails.getUsername());
        if(user == null){
            return DataMap.fail(CodeType.SERVER_EXCEPTION);
        }
        articleLikesRecord.setLikerId(user.getId());
        articleLikesRecord.setLikeDate(timeUtil.getFormatDateForFive());
        articleLikesRecord.setIsRead(1);
        String articleKey =String.valueOf(articleLikesRecord.getArticleId());

        //判断是否已经点赞
        if (statisticMapper.findlike(user.getId(),articleLikesRecord.getArticleId()) == 0){
            statisticMapper.saveLikeInfo(articleLikesRecord);

            Object likes = redisTemplate.opsForHash().get("likes", articleKey);
            if (likes == null){
                likes = statisticMapper.getLikeNum(articleLikesRecord.getArticleId());//后期修改为从文章表获取
                redisTemplate.opsForHash().put("likes", articleKey,(int)likes + 1);
            }else {
                redisTemplate.opsForHash().put("likes", articleKey,(int)likes + 1);
            }
        }else {
            return DataMap.fail(CodeType.MESSAGE_HAS_THUMBS_UP);
        }


        return DataMap.success();
    }
}
